package com.xhh.nphm.system.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xhh.nphm.common.core.domain.entity.Dept;
import com.xhh.nphm.system.domain.TWorkcsbase;
import com.xhh.nphm.system.mapper.TWorkcsbaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.xhh.nphm.common.annotation.DataScope;
import com.xhh.nphm.common.constant.UserConstants;
import com.xhh.nphm.common.core.domain.Ztree;
import com.xhh.nphm.common.core.domain.entity.SysRole;
import com.xhh.nphm.common.exception.BusinessException;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.system.mapper.DeptMapper;
import com.xhh.nphm.system.service.IDeptService;

/**
 * 部门管理 服务实现
 *
 * @author ydq
 */
@Service
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private TWorkcsbaseDao tWorkcsbaseDao;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Dept> selectDeptList(Dept dept) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        if(dept.getDeptName()!=null&&dept.getDeptName().length()!=0) queryWrapper.like("DeptName",dept.getDeptName());
        if(dept.getUseState()>-1) queryWrapper.eq("UseState",dept.getUseState());
        queryWrapper.orderByAsc("NoUnit");
        return deptMapper.selectList(queryWrapper);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTree(Dept dept) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("NoUnit","");
        if(dept.getDeptName()!=null) queryWrapper.eq("DeptName",dept.getDeptName());
        if(dept.getUseState()>0) queryWrapper.eq("UseState",dept.getUseState());
        List<Dept> deptList = deptMapper.selectList(queryWrapper);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param dept 部门ID
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTreeExcludeChild(Dept dept) {
        String deptId = dept.getNoUnit();
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("NoUnit","");
        if(dept.getDeptName()!=null) queryWrapper.eq("DeptName",dept.getDeptName());
        if(dept.getUseState()>0) queryWrapper.eq("UseState",dept.getUseState());
        List<Dept> deptList = deptMapper.selectList(queryWrapper);
        Iterator<Dept> it = deptList.iterator();
        while (it.hasNext()) {
            Dept d = (Dept) it.next();
            if (d.getNoUnit().equals(deptId)) {//|| ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<Dept> deptList = selectDeptList(new Dept());
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DeptName");
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleDeptList = new ArrayList<>();
            for (Dept dept:
                    deptMapper.selectList(queryWrapper)) {
                roleDeptList.add(dept.getDeptName());
            }
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }



    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Dept> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Dept> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (Dept dept : deptList) {
            if (dept.getUseState()==1) {
                Ztree ztree = new Ztree();
                ztree.setId(Long.parseLong(dept.getNoUnit()));
                ztree.setpId(Long.parseLong(dept.getNoParent()==null ? "0" : dept.getNoParent()));
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck) {
                    ztree.setChecked(roleDeptList.contains(dept.getNoUnit() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        Dept dept = new Dept();
        dept.setNoParent(parentId+"");
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        if(dept.getNoUnit()!=null)
        queryWrapper.eq("NoUnit",dept.getNoUnit());
        if(dept.getNoParent()!=null)
            queryWrapper.eq("NoParent",dept.getNoParent());
        return deptMapper.selectCount(queryWrapper);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("NoUnit",deptId+"");
        int result = deptMapper.selectCount(queryWrapper);
        return result > 0 ? true : false;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        Map<String,Object> map = new HashMap<>();
        map.put("noUnit",deptId+"");
        return deptMapper.deleteByMap(map);
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(Dept dept) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("NoUnit",dept.getNoParent());
        Dept info = deptMapper.selectList(queryWrapper)==null||deptMapper.selectList(queryWrapper).size()==0 ?  null : deptMapper.selectList(queryWrapper).get(0);
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (info.getUseState()!=1) {
            throw new BusinessException("部门停用，不允许新增");
        }
        return deptMapper.insert(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(Dept dept) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("NoParent",dept.getNoParent());
        Dept newParentDept = deptMapper.selectList(queryWrapper)==null||deptMapper.selectList(queryWrapper).size()==0 ?  null : deptMapper.selectList(queryWrapper).get(0);

        Dept oldDept = selectDeptById(Long.parseLong(dept.getNoUnit()));
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {


        }
        queryWrapper.clear();
        queryWrapper.eq("NoUnit",dept.getNoUnit());
        int result = deptMapper.update(dept,queryWrapper);
        return result;
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public Dept selectDeptById(Long deptId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("NoUnit",deptId+"");
        return deptMapper.selectList(queryWrapper)==null||deptMapper.selectList(queryWrapper).size()==0 ?  null : deptMapper.selectList(queryWrapper).get(0);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(String deptId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("NoParent",deptId+"");
        return deptMapper.selectCount(queryWrapper);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(Dept dept) {
        String deptId = StringUtils.isNull(dept.getNoUnit()) ? "-1" : dept.getNoUnit();
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DeptName",dept.getDeptName()).eq("NoParent",dept.getNoParent());
        List<Dept> info = deptMapper.selectList(queryWrapper);
        if (info!=null&&info.size()>1) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    /**
     * 查询派发单位列表
     * @return
     */
    @Override
    public List<Map<String,String>> selectDistribute() {
        return deptMapper.selectDistribute();
    }

    @Override
    public List<Map<String, String>> selectSltDept() {
        return deptMapper.selectSltDept();
    }

    /**
     * 查询部门（抄送）
     * @param wfId 根据工单编号查询抄送件所属部门,进行回显选中
     * @return 部门树数据 List<Ztree>
     */
    @Override
    public List<Ztree> copyDeptTreeData(Integer wfId) {
        List<Ztree> ztrees = new ArrayList<Ztree>(){{
            add(new Ztree(1L,0L,"市级部门","市级部门"));
            add(new Ztree(2L,0L,"区(市)县","区(市)县"));
            add(new Ztree(3L,0L,"直派(工商)","直派(工商)"));
            add(new Ztree(4L,0L,"直派(食药监)","直派(食药监)"));
            add(new Ztree(5L,0L,"直派(城管)","直派(城管)"));
            add(new Ztree(6L,0L,"直派(旅游)","直派(旅游)"));
            add(new Ztree(301910876L,3L,"天府新区城市管理和市场监管局","天府新区城市管理和市场监管局"));
            add(new Ztree(359040L,3L,"锦江区市场监管局","锦江区市场监管局"));
            add(new Ztree(359050L,3L,"青羊区市场监管局","青羊区市场监管局"));
            add(new Ztree(359060L,3L,"武侯区市场监管局","武侯区市场监管局"));
            add(new Ztree(359080L,3L,"成华区工商局","成华区工商局"));
            add(new Ztree(359120L,3L,"龙泉驿区工商局","龙泉驿区工商局"));
            add(new Ztree(359130L,3L,"青白江区工商局","青白江区工商局"));
            add(new Ztree(363140L,3L,"新都区市场监管局","新都区市场监管局"));
            add(new Ztree(359150L,3L,"温江区工商局","温江区工商局"));
            add(new Ztree(359210L,3L,"金堂县工商局","金堂县工商局"));
            add(new Ztree(359220L,3L,"双流县市场监管局","双流县市场监管局"));
            add(new Ztree(363240L,3L,"郫县市场监督管理局","郫县市场监督管理局"));
            add(new Ztree(359290L,3L,"大邑县工商局","大邑县工商局"));
            add(new Ztree(359310L,3L,"蒲江县市场监督管理局","蒲江县市场监督管理局"));
            add(new Ztree(363320L,3L,"新津县市场监管局","新津县市场监管局"));
            add(new Ztree(363810L,3L,"都江堰市市场监督管理局","都江堰市市场监督管理局"));
            add(new Ztree(359820L,3L,"彭州市市场监管局","彭州市市场监管局"));
            add(new Ztree(359830L,3L,"邛崃市市场监管局","邛崃市市场监管局"));
            add(new Ztree(359840L,3L,"崇州市市场监管局","崇州市市场监管局"));
            add(new Ztree(359090L,3L,"高新区工商局","高新区工商局"));
            add(new Ztree(335040L,5L,"锦江区城管局","锦江区城管局"));
            add(new Ztree(335050L,5L,"青羊区城管局","青羊区城管局"));
            add(new Ztree(335060L,5L,"金牛区城管局","金牛区城管局"));
            add(new Ztree(335070L,5L,"武侯区城管局","武侯区城管局"));
            add(new Ztree(335080L,5L,"成华区城管局","成华区城管局"));
            add(new Ztree(335120L,5L,"龙泉驿区城管局","龙泉驿区城管局"));
            add(new Ztree(335130L,5L,"青白江区城管局","青白江区城管局"));
            add(new Ztree(335140L,5L,"新都区城管局","新都区城管局"));
            add(new Ztree(335150L,5L,"温江区城管局","温江区城管局"));
            add(new Ztree(335210L,5L,"金堂县城管局","金堂县城管局"));
            add(new Ztree(335220L,5L,"双流县城管局","双流县城管局"));
            add(new Ztree(335240L,5L,"郫县城管局","郫县城管局"));
            add(new Ztree(335290L,5L,"大邑县城管局","大邑县城管局"));
            add(new Ztree(335310L,5L,"蒲江县城管局","蒲江县城管局"));
            add(new Ztree(335320L,5L,"新津县城管局","新津县城管局"));
            add(new Ztree(335810L,5L,"都江堰市城管局","都江堰市城管局"));
            add(new Ztree(335820L,5L,"彭州市城管局","彭州市城管局"));
            add(new Ztree(335090L,5L,"高新区城管局","高新区城管局"));
            add(new Ztree(301910876L,5L,"天府新区城市管理和市场监管局","天府新区城市管理和市场监管局"));
            add(new Ztree(335840L,5L,"崇州市城管局","崇州市城管局"));
            add(new Ztree(359040L,4L,"锦江区市场监管局","锦江区市场监管局"));
            add(new Ztree(359050L,4L,"青羊区市场监管局","青羊区市场监管局"));
            add(new Ztree(359060L,4L,"金牛区市场监督管理局","金牛区市场监督管理局"));
            add(new Ztree(359070L,4L,"武侯区市场监管局","武侯区市场监管局"));
            add(new Ztree(359080L,4L,"成华区市场监督管理局","成华区市场监督管理局"));
            add(new Ztree(363120L,4L,"龙泉驿区食药监局","龙泉驿区食药监局"));
            add(new Ztree(363130L,4L,"青白江区食药监局","青白江区食药监局"));
            add(new Ztree(363140L,4L,"新都区市场监管局","新都区市场监管局"));
            add(new Ztree(359150L,4L,"温江区市场监管局","温江区市场监管局"));
            add(new Ztree(363210L,4L,"金堂县食药监局","金堂县食药监局"));
            add(new Ztree(359220L,4L,"双流县市场监管局","双流县市场监管局"));
            add(new Ztree(363240L,4L,"郫县市场监督管理局","郫县市场监督管理局"));
            add(new Ztree(363290L,4L,"大邑县食药监局","大邑县食药监局"));
            add(new Ztree(359310L,4L,"蒲江县市场监督管理局","蒲江县市场监督管理局"));
            add(new Ztree(363320L,4L,"新津县市场监管局","新津县市场监管局"));
            add(new Ztree(363810L,4L,"都江堰市市场监督管理局","都江堰市市场监督管理局"));
            add(new Ztree(359820L,4L,"彭州市市场监管局","彭州市食药监局"));
            add(new Ztree(359830L,4L,"邛崃市市场监管局","邛崃市市场监管局"));
            add(new Ztree(359840L,4L,"崇州市市场监管局","崇州市市场监管局"));
            add(new Ztree(363090L,4L,"高新区食药监局","高新区食药监局"));
            add(new Ztree(301910876L,4L,"天府新区城市管理和市场监管局","天府新区城市管理和市场监管局"));
            add(new Ztree(373040L,6L,"锦江区旅游局","锦江区旅游局"));
            add(new Ztree(301050804L,6L,"青羊区文体旅局","青羊区文体旅局"));
            add(new Ztree(301060810L,6L,"金牛区文化旅游和体育局","金牛区文化旅游和体育局"));
            add(new Ztree(301070807L,6L,"武侯区文体局","武侯区文体局"));
            add(new Ztree(301080804L,6L,"成华区文旅体局","成华区文旅体局"));
            add(new Ztree(301120828L,6L,"龙泉驿区文旅局","龙泉驿区文旅局"));
            add(new Ztree(301130807L,6L,"青白江区旅发局","青白江区旅发局"));
            add(new Ztree(301140801L,6L,"新都区商务和旅游局","新都区商务和旅游局"));
            add(new Ztree(373150L,6L,"温江区旅游局","温江区旅游局"));
            add(new Ztree(373210L,6L,"金堂县旅游局","金堂县旅游局"));
            add(new Ztree(301220834L,6L,"双流县文旅局","双流县文旅局"));
            add(new Ztree(301240813L,6L,"郫县文旅体广新局","郫县文旅体广新局"));
            add(new Ztree(373290L,6L,"大邑县旅游局","大邑县旅游局"));
            add(new Ztree(373310L,6L,"蒲江县旅游局","蒲江县旅游局"));
            add(new Ztree(373320L,6L,"新津县旅游局","新津县旅游局"));
            add(new Ztree(373810L,6L,"都江堰市旅游局","都江堰市旅游局"));
            add(new Ztree(301820858L,6L,"彭州市文广旅局","彭州市文广旅局"));
            add(new Ztree(301830825L,6L,"邛崃市文广新局","邛崃市文广新局"));
            add(new Ztree(301840804L,6L,"崇州市文体广新局","崇州市文体广新局"));
            add(new Ztree(301090804L,6L,"高新区社事局","高新区社事局"));
            add(new Ztree(301910810L,6L,"天府新区科技宣传局","天府新区科技宣传局"));
            add(new Ztree(301840861L,6L,"崇州市综合行政执法局","崇州市综合行政执法局"));
        }};
        QueryWrapper<Dept> flatDeptWrapper = new QueryWrapper<>();
        flatDeptWrapper
                .eq("areaNo","5101")
                .eq("LEN(noUnit)","3")
                .eq("UseState",1)
                .eq("isDel",0);
        List<Dept> flatDeptList = deptMapper.selectList(flatDeptWrapper);
        QueryWrapper<Dept> sonDeptWrapper = new QueryWrapper<>();
        sonDeptWrapper
                .eq("noParent","304")
                .eq("UseState",1)
                .eq("isDel",0);
        List<Dept> sonDeptList = deptMapper.selectList(sonDeptWrapper);
        for (Dept dept : flatDeptList) {
            if (dept.getUseState()==1) {
                Ztree ztree = new Ztree();
                ztree.setId(Long.parseLong(dept.getNoUnit()));
                ztree.setpId(Long.parseLong("1"));
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                ztrees.add(ztree);
            }
        }
        for (Dept dept : sonDeptList) {
            if (dept.getUseState()==1) {
                Ztree ztree = new Ztree();
                ztree.setId(Long.parseLong(dept.getNoUnit()));
                ztree.setpId(Long.parseLong("2"));
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                ztrees.add(ztree);
            }
        }
        ztrees = nodeCheck(wfId,ztrees);
        return ztrees;
    }

    /**
     * 2023/1/11
     * 根据部门名称查询部门信息
     * @return
     */
    @Override
    public Dept selectDeptByDeptName(String deptName) {
        return deptMapper.selectDeptByDeptName(deptName);
    }

    /**
     * 设置回显时要选中的部门
     * @param wfId 抄送件工单编号
     * @param ztrees 部门树列表
     * @return 部门树列表数据
     */
    public List<Ztree> nodeCheck(Integer wfId,List<Ztree> ztrees){
        //查询抄送件表中是否存在该数据
        QueryWrapper<TWorkcsbase> queryWrapper = Wrappers.query();
        queryWrapper.eq("wfId",wfId);
        //该工单编号的抄送件记录列表
        List<TWorkcsbase> list = tWorkcsbaseDao.selectList(queryWrapper);
        for (TWorkcsbase tWorkcsbase : list) {
            for (Ztree ztree:ztrees) {
                //如果部门编号在抄送件记录列表中存在
                if (ztree.getId() == tWorkcsbase.getDeptId().longValue()) {
                    //就设置选中
                    ztree.setChecked(true);
                }
            }
        }
        return ztrees;
    }
}
